package com.wen.controller;

import com.github.pagehelper.PageInfo;
import com.wen.pojo.Product;
import com.wen.service.ProductService;
import com.wen.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * @author 20212
 * 产品
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    /**
     * 查询全部
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAll")
    @RolesAllowed("ADMIN")
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1")Integer page,
                                @RequestParam(name = "size", required = true, defaultValue = "4")Integer size) throws Exception {
      ModelAndView model = new ModelAndView();
        List<Product> all = productService.findAll(page, size);

        PageInfo pageInfo = new PageInfo(all);

        model.addObject("pageInfo", pageInfo);
        model.setViewName("product-list");
        return model;
    }

    @RequestMapping("/findById")
    public ModelAndView findById(Integer id) throws Exception {
        ModelAndView model = new ModelAndView();
        Product byId = productService.findById(id);
        model.addObject("product", byId);
        model.setViewName("product-show");
        return model ;


    }

    @RequestMapping("/save")
    public String save(Product product) throws Exception {
        System.out.println("=>"+product.getDepartureTime());
        System.out.println("=>"+product.getDepartureTimeStr());
        productService.add(product);
        return "redirect:/product/findAll";

    }

    @RequestMapping("/deleteById")
    public String deleteById(int id) throws Exception {
        productService.deleteById(id);
        return "redirect:/product/findAll";
    }

    @RequestMapping("/toUpdateById")
    public ModelAndView toUpdateById(Integer id) throws Exception {
        ModelAndView model = new ModelAndView();
        Product byId = productService.findById(id);
        model.addObject("product", byId);
        model.setViewName("product-update");
        return model ;

    }

    @RequestMapping("updateById")
    public String upDateById(Product product) throws Exception{
        product.setDepartureTime(DateUtils.string2Date(product.getDepartureTimeStr(),"yyyy-MM-dd HH:mm"));
        System.out.println("=>"+product.getDepartureTime());
        System.out.println("=>"+product.getDepartureTimeStr());
        productService.updateById(product);
        return "redirect:/product/findAll";
    }


}
